﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.IO;
using System.Configuration;
using System.Reflection;

namespace JohnnySins.Code
{
    public class BasePage : Page
    {
        public string jwplayerKey = ConfigurationManager.AppSettings["jwplayer.key"];
        public string JsCodeToRunOnReady { get; set; }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            JsCodeToRunOnReady = "";
        }

        public bool IsAuthentificated
        {
            get { return System.Web.HttpContext.Current.User.Identity.IsAuthenticated; }
        }

        public string BasePath
        {
            get { return ResolveClientUrl("~"); }
        }

        public string BasePathAbs
        {
            get { return ResolveClientUrl("~"); }
        }

        public bool IsAdmin
        {
            get
            {
                if (CurrentProviderUserId != null)
                    return Roles.IsUserInRole("admin");

                return false;
            }

        }

        public int? CurrentUserId
        {
            get { return (int?)Context.Session["userId"]; }
            set { Context.Session.Add("userId", value); }
        }

        public string CurrentUserName
        {
            get { return Context.Session["userName"] == null ? "" : Context.Session["userName"].ToString(); }
            set { Context.Session.Add("userName", value); }
        }

        public Guid? CurrentProviderUserId
        {
            get
            {
                var user = Membership.GetUser(CurrentUserName);
                if (user != null)
                    return (Guid?)user.ProviderUserKey;
                return (Guid?)null;
            }
        }

        protected string GetIPAddress()
        {
            return Request.UserHostAddress;
        }

        protected void AlertAndClear(string message)
        {
            Response.Clear();
            Response.Write(string.Format("<script type=\"text/javascript\">alert('{0}');</script>", message));
            Response.End();
        }

        public static void DeleteFile(string fileName)
        {
            if (File.Exists(fileName))
                try
                {
                    File.Delete(fileName);
                }
                catch (Exception ex) { }
        }

        public static string Version()
        {
            Assembly ass = Assembly.GetExecutingAssembly();
            AssemblyName assName = ass.GetName();
            return assName.Version.ToString();
        }

    }
}
